package com.mytrans.client;

import com.mytrans.beans.TranceRecordBean;
import com.mytrans.transaction.DefaultTransactionListener;
import com.mytrans.util.ServletUtil;
import com.zhou.util.JsonUtil;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ListenerServlet extends HttpServlet {

    public final DefaultTransactionListener transactionListener;

    public ListenerServlet(DefaultTransactionListener transactionListener) {
        this.transactionListener = transactionListener;
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String body = ServletUtil.getRequestBody(req);
            TranceRecordBean bean = JsonUtil.getGson().fromJson(body, TranceRecordBean.class);
            transactionListener.commitListener(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.getWriter().println();
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        try {
            String body = ServletUtil.getRequestBody(req);
            TranceRecordBean bean = JsonUtil.getGson().fromJson(body, TranceRecordBean.class);
            transactionListener.rollBackListener(bean);
        } catch (Exception e) {
            e.printStackTrace();
        }
        resp.getWriter().println();
    }
}
